const mongoose = require('mongoose');

const CompetitorSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
    required: true
  },
  site: {
    type: mongoose.Schema.ObjectId,
    ref: 'Site',
    required: true
  },
  domain: {
    type: String,
    required: [true, '请输入竞争对手域名'],
    trim: true
  },
  stats: {
    domainAuthority: {
      type: Number,
      default: 0
    },
    backlinks: {
      type: Number,
      default: 0
    },
    organicTraffic: {
      type: Number,
      default: 0
    },
    rankingKeywords: {
      type: Number,
      default: 0
    }
  },
  analysisHistory: [
    {
      date: {
        type: Date,
        default: Date.now
      },
      data: Object
    }
  ],
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

// 更新updatedAt字段
CompetitorSchema.pre('save', function(next) {
  this.updatedAt = Date.now();
  next();
});

// 确保每个用户对同一网站的竞争对手是唯一的
CompetitorSchema.index({ user: 1, site: 1, domain: 1 }, { unique: true });

module.exports = mongoose.model('Competitor', CompetitorSchema);